/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ibmmodel3;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import jdbm.RecordManager;
import jdbm.RecordManagerFactory;
import jdbm.RecordManagerOptions;
import jdbm.htree.HTree;

/**
 *
 * @author mwh
 */
public class DistortionTableJDBM implements DistortionTable {

    RecordManager recman;

    HTree distortions;

    final int targetLength;


    public DistortionTableJDBM(DistortionTableMem dtMem, String dbName) throws IOException {

        Properties props = new Properties();

        props.setProperty(RecordManagerOptions.DISABLE_TRANSACTIONS, "true");

        recman = RecordManagerFactory.createRecordManager("/home/mwh/DGS/databases/" + dbName + ".jdbm", props);

        // Create idToName hash-distortions and add TOP as element;
        distortions = HTree.createInstance(recman);
        recman.setNamedObject("distortions", distortions.getRecid());


        for (Iterator<DistortionKey> keyIt = dtMem.keyIterator(); keyIt.hasNext();) {

            DistortionKey key = keyIt.next();
            Double dist = dtMem.get(key);

            distortions.put(key.asList(), dist);
            recman.commit();

        }
        targetLength = dtMem.getTargetLength();

        long tdid = recman.insert(targetLength);
        recman.setNamedObject("targetLength", tdid);

        recman.commit();

    }


    public DistortionTableJDBM(String dbName) throws IOException {


        Properties props = new Properties();

        props.setProperty(RecordManagerOptions.DISABLE_TRANSACTIONS, "true");

        recman = RecordManagerFactory.createRecordManager("/home/mwh/DGS/databases/" + dbName + ".jdbm", props);
        long recid = recman.getNamedObject("distortions");

        distortions = HTree.load(recman, recid);

        // Get ID for targetLength load targetLenth
        long tdid = recman.getNamedObject("targetLength");
        targetLength = (Integer) recman.fetch(tdid);

    }


    public double get(DistortionKey k) {
        try {
            List<Integer> kL = new ArrayList<Integer>(k.asList());
            kL.set(3, targetLength);
            return (Double) distortions.get(kL);
        } catch (IOException ex) {
            Logger.getLogger(TranslationTableJDBM.class.getName()).log(Level.SEVERE, null, ex);
        }

        return Double.NaN;
    }


    public double getLog10(DistortionKey k) {
        return Math.log10(get(k));
    }
}
